package me.android.library.utils.android;

import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;

import com.google.common.collect.Sets;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import lombok.Data;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import mylab.utils.common.CollectionUtil;

@Slf4j
@UtilityClass
public class UsbUtil {

    @Data
    public static class PortParameter {
        int baudRate = 115200;
        int dataBits = UsbSerialPort.DATABITS_8;
        int stopBits = UsbSerialPort.STOPBITS_1;
        int parity = UsbSerialPort.PARITY_NONE;
    }

    // 打开指定设备
    public UsbSerialPort openDevice(UsbSerialDriver driver, PortParameter parameter) {
        try {
            UsbManager manager = SystemServiceUtil.getUsbManager();
            UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
            if (connection == null) {
                //manager.requestPermission(driver.getDevice(), ..) handling here
                return null;
            }

            if (CollectionUtil.isEmpty(driver.getPorts())) {
                return null;
            }

            // Most devices have just one port (port 0)
            UsbSerialPort port = driver.getPorts().get(0);
            port.open(connection);
            port.setParameters(parameter.getBaudRate(), parameter.getDataBits(), parameter.getStopBits(), parameter.getParity());
            return port;
        } catch (IOException e) {
            log.warn("openDevice error",e);
            return null;
        }
    }

    public void closeDevice(UsbSerialPort serialPort){
        try {
            serialPort.close();
        } catch (IOException e) {
            log.warn("close serialPort error",e);
        }
    }

    public Set<UsbSerialPort> getUsbSerialPorts() {
        Set<UsbSerialPort> ports = Sets.newHashSet();
        List<UsbSerialDriver> drivers = getUsbSerialDrivers();
        for (UsbSerialDriver usbSerialDriver : drivers) {
            ports.addAll(usbSerialDriver.getPorts());
        }
        return ports;
    }

    public List<UsbSerialDriver> getUsbSerialDrivers() {
        UsbManager manager = SystemServiceUtil.getUsbManager();
        return UsbSerialProber.getDefaultProber().findAllDrivers(manager);
    }
}
